from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QColor
from Processor.histogram.histogram_design import Ui_HistogramWidget

import time
import cv2
import Processor.Converter as Converter


class HistogramWidget(QDialog, Ui_HistogramWidget):
    layer = None    # 图层
    mat = None  # 原始Mat 数据
    grayMat = None # 灰度图数据
    # 通道直方图颜色
    channelColor = (QColor(200, 200, 200), QColor(220, 20, 60), QColor(60, 179, 113), QColor(0, 191, 255))

    def __init__(self, parent, mat=None):
        super().__init__(parent)
        self.setupUi(self)
        self.initUI(parent)
        # 第一次显示直方图
        self.mat = mat
        self.grayMat = cv2.cvtColor(mat, cv2.COLOR_RGBA2GRAY)  # 灰度图
        self.canvas.histogramData = self.__histogram()
        self.canvas.color = self.channelColor[0]
        self.show()

    def initUI(self, parent):

        self.setWindowTitle('灰度直方图')
        # 定位
        pos = parent.geometry()
        self.move((pos.width() - self.width())/2, (pos.height() - self.height())/2)
        #       信号
        # 确定
        # self.DialogButtonBox.accepted.connect(self.accept)
        # 通道切换
        self.comboBox_channel.currentIndexChanged.connect(self.updateSlot)
        # 分辨率
        self.spinBox_Bin.valueChanged.connect(self.updateSlot)

    def updateSlot(self):
        channel = self.comboBox_channel.currentIndex()
        bin = self.spinBox_Bin.value()
        self.canvas.histogramData = self.__histogram(channel, bin)
        self.canvas.color = self.channelColor[channel]
        self.canvas.update()

    def __histogram(self, channel=0, bin=256):
        """
        生成直方图
        :param channel: 0 全部， 1 R, 2 G, 3 B
        :param bin: 组合数大小，分辨率
        :return: 归一化的nx1 矩阵（归一化到最大值）
        """
        start = time.perf_counter()
        if channel == 0:
            mat = self.grayMat
        else:
            mat = self.mat
            channel = channel - 1
        hist = cv2.calcHist([mat], [channel], None, [bin], [0, 256])
        end = time.perf_counter()
        print('histogram', '耗时：', end - start)
        return hist / hist.max()    # 归一化


def newHistogram(window):
    """
    :param window: 主窗体
    :return:
    """
    layer = window.currentLayer
    if layer:
        image = layer.image  # 当前图层QImage句柄
        mat = Converter.QImage2Numpy(image)
        controller = HistogramWidget(window, mat)
        controller.layer = layer
